import json
from flask import Flask, request, jsonify
from datetime import datetime
import sys
from pathlib import Path

# 添加上级目录到系统路径，以便导入其他模块
sys.path.append(str(Path(__file__).parent.parent))

from database.db_connection import execute_query
from backend.utils.logger import setup_logger

# 设置日志
logger = setup_logger('leave_application')

app = Flask(__name__)

class LeaveApplicationHandler:
    """ 处理请假申请的类 """

    @staticmethod
    def process_leave_request(employee_id, leave_type, start_date, end_date, reason):
        """
        处理请假申请并存入数据库。

        Args:
            employee_id (str): 员工ID
            leave_type (str): 请假类型 ('sick', 'personal', 'vacation', 'other')
            start_date (str): 开始日期 (格式: YYYY-MM-DD)
            end_date (str): 结束日期 (格式: YYYY-MM-DD)
            reason (str): 请假原因

        Returns:
            dict: 申请结果
        """
        try:
            # 检查必要字段
            if not all([employee_id, leave_type, start_date, end_date]):
                return {"success": False, "message": "请填写所有必填字段"}

            # 确保日期格式正确
            try:
                start_date = datetime.strptime(start_date, "%Y-%m-%d").date()
                end_date = datetime.strptime(end_date, "%Y-%m-%d").date()
            except ValueError:
                return {"success": False, "message": "日期格式错误，必须为 YYYY-MM-DD"}

            # 检查开始日期是否早于结束日期
            if start_date > end_date:
                return {"success": False, "message": "开始日期不能晚于结束日期"}
                
            # 验证员工是否存在
            employee_query = "SELECT employee_id FROM employees WHERE employee_id = %s"
            employee_result = execute_query(employee_query, (employee_id,))
            
            if not employee_result:
                logger.warning(f"尝试提交请假申请的员工ID不存在: {employee_id}")
                return {"success": False, "message": "员工ID不存在，请检查并重新输入"}

            logger.info(f"提交请假申请: {employee_id}, {leave_type}, {start_date} - {end_date}")

            # 插入请假记录，并返回生成的 ID
            insert_query = """
                INSERT INTO leave_requests 
                (employee_id, leave_type, start_date, end_date, reason, status) 
                VALUES (%s, %s, %s, %s, %s, 'pending')
            """
            lastrowid = execute_query(insert_query, (employee_id, leave_type, start_date, end_date, reason), fetch=False)

            if lastrowid:
                logger.info(f"请假申请提交成功: {employee_id}, ID: {lastrowid}")
                return {"success": True, "message": "请假申请提交成功，等待审批", "leave_id": lastrowid}
            else:
                return {"success": False, "message": "数据库插入失败，请重试"}

        except Exception as e:
            logger.error(f"请假申请提交失败: {e}")
            return {"success": False, "message": f"提交失败: {str(e)}"}

if __name__ == '__main__':
    app.run(debug=True)
